package com.example.springbooteasycode.utils.qrcode.withText;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Paths;

public class QRCodeWithText {
    public static void main(String[] args) throws WriterException, IOException {
        String text = "Hello, World!";
        int width = 300;
        int height = 300;
        String filePath = "qrcodeNew.png";

        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
        BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
        Graphics2D graphics2D = image.createGraphics();

        // 设置字体和颜色
        Font font = new Font("Arial", Font.BOLD, 18);
        graphics2D.setColor(Color.BLACK);
        graphics2D.setFont(font);

        // 设置文字平滑
        graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // 设置文字位置
        int fontRadius = (int) (height / 10.0);
        int fontX = (width - fontRadius * 2) / 2;
        int fontY = (height - fontRadius * 2) / 2;
        int fontStartY = fontY + fontRadius;

        // 画圆作为背景
        int ovalWidth = fontRadius * 2;
        int ovalHeight = fontRadius * 2;
        graphics2D.drawOval(fontX, fontStartY - ovalHeight, ovalWidth, ovalHeight);

        // 画文字
        graphics2D.drawString(text, fontX + ovalWidth / 2 - 4, fontStartY + fontRadius / 2 + 3);

        // 释放资源
        graphics2D.dispose();

        // 输出图片
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", Paths.get(filePath));
    }
}
